package com.yc.book;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

@MultipartConfig
@WebServlet(name = "GetUploadServlet", value = "/upload/*")

public class GetUploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        String path = request.getRequestURI().replace(request.getContextPath(), "");
        String file = path.replace("/upload/", "");
        System.out.println(file);
        String diskPath = "D:\\imagesss\\" + file;
        System.out.println("diskPath=" + diskPath);
        String contentTyep = getServletContext().getMimeType(diskPath);
        response.setContentType(contentTyep);
        ServletOutputStream out = response.getOutputStream();
        try (FileInputStream fis = new FileInputStream(diskPath)

        ) {
            byte[] bytes = new byte[1024];
            int cout;
            while ((cout = fis.read(bytes)) != 0) {
                out.write(bytes, 0, cout);
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
